<template>
  <div v-loading="loading" class="dataForm">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <div class="no-print">
        <el-row>
          <el-col :span="24">
            <el-form-item v-if="!$route.query.id" :label="$t('项目名称')" prop="dealId">
              <MainBodySelect
                v-model="form.dealId"
                :show-label="false"
                :parameters="'deal'"
                @change="changeDeal"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('申请标题')" prop="actTitle">
              <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" @change="processPhaseActTitle = undefined" @input="actTitleInput($event)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('申请人')" prop="applyUser">
              <UserSelect
                v-model="form.applyUser"
                :placeholder="$t('申请人')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('申请时间')" prop="applyTime">
              <DatePicker v-model="form.applyTime" :placeholder="$t('申请时间')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="typeSub">
              <span slot="label">
                {{ $t('划款类型') }}
                <el-tooltip :content="$t('类型为“投资款”时,审批完成后将划款信息同步至投资主体')" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-select v-model="form.typeSub" :placeholder="$t('划款类型')">
                <el-option
                  v-for="dict in typeMainOption"
                  :key="dict.dictValue"
                  :label="$t(dict.dictLabel)"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-show="false" :span="12">
            <el-form-item :label="$t('币种')" prop="currency">
              <Currency v-model="form.currency" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('关联合同')" prop="contractId">
              <div style="display: flex;">
                <el-select v-model="form.contractId" :placeholder="$t('关联合同')" style="width: 88% !important;" @change="contractChange(form.contractId)">
                  <el-option
                    v-for="(item, index) in contractOptions"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <el-button slot="append" icon="el-icon-view" @click="viewContractPage(form.contractId)" />
              </div>
            </el-form-item>
          </el-col>
          <el-col v-show="false" :span="12">
            <el-form-item :label="$t('划款方式')" prop="method">
              <el-radio-group v-model="form.method">
                <el-radio
                  v-for="item in methodOptions"
                  :key="item.dictValue"
                  :label="item.dictValue"
                > {{ $t(item.dictLabel) }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('紧急级别')" prop="level">
              <el-radio-group v-model="form.level">
                <el-radio
                  v-for="item in levelOptions"
                  :key="item.dictValue"
                  :label="item.dictValue"
                > {{ $t(item.dictLabel) }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.contractId && form.contractAmount !== 0 && form.contractAmount !== undefined && form.contractAmount !== null" :span="12">
            <el-form-item :label="$t('是否满足先决条件')" prop="meetPrerequisites">
              <dictSelect
                v-model="form.meetPrerequisites"
                dictionary="deal_satisfaction_status"
              />
            </el-form-item>
          </el-col>
          <el-col v-show="form.contractId && form.contractAmount !== 0 && form.contractAmount !== undefined && form.contractAmount !== null" :span="12">
            <el-form-item :label="$t('合同金额')+ $t('金额单位')" prop="contractAmount">
              <Money v-model="form.contractAmount" unit="w" disabled />
            </el-form-item>
          </el-col>
          <el-col v-if="contractType === 'contractPayables'" :span="12">
            <el-form-item :label="$t('合同应划款金额')+ $t('金额单位')" prop="contractPayables">
              <Money v-model="form.contractPayables" unit="w" :placeholder="$t('合同应划款金额')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-show="form.contractId" :label="$t('划款金额') + $t('金额单位')" prop="total">
              <Money v-model="form.total" unit="w" disabled :placeholder="$t('请在划款主体列表中维护')" />
            </el-form-item>
          </el-col>
          <el-col v-show="false" :span="12">
            <el-form-item :label="$t('本次划款金额') + $t('金额单位')" prop="amountOfThisPayment">
              <Money v-model="form.amountOfThisPayment" unit="w" disabled />
            </el-form-item>
          </el-col>
          <el-col v-show="form.contractId && paymentPrerequisitesShow" :span="24">
            <el-form-item :label="$t('划款先决条件')">
              <el-input v-model="paymentPrerequisites" type="textarea" :disabled="true" show-word-limit maxlength="2000" :placeholder="$t('划款先决条件')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('备注')" prop="remark">
              <el-input v-model="form.remark" type="textarea" show-word-limit maxlength="2000" :placeholder="$t('备注')" />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="area-header" style="margin-top: 15px;">
          <span class="area-header-title">{{ $t('收款方信息') }}</span>
        </div>
        <!--
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('收款方名称')" prop="payeeName">
            <el-autocomplete
              v-model="form.payeeName"
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch"
              :maxlength="100"
              :placeholder="$t('收款方名称')"
              @select="handleSelect"
            >
              <i slot="suffix" class="el-icon-edit" @click="handleIconClick">.</i>
              <template slot-scope="{ item }">
                <div class="name">{{ item.value }}</div>
                <span class="addr">{{ item.address }}</span>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('开户行名称')" prop="depositBank">
            <el-input v-model="form.depositBank" show-word-limit :maxlength="100" :placeholder="$t('开户行名称')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('账户名称')" prop="accountTitle">
            <el-input v-model="form.accountTitle" show-word-limit :maxlength="100" :placeholder="$t('账户名称')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('银行账号')" prop="bankNumber">
            <el-input v-model="form.bankNumber" show-word-limit :maxlength="100" :placeholder="$t('银行账号')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('收款方地址')" prop="addressReceiver">
            <el-input v-model="form.addressReceiver" type="textarea" show-word-limit :maxlength="200" :autosize="{ minRows: 1 }" :placeholder="$t('收款方地址')" />
          </el-form-item>
        </el-col>
      </el-row>
      -->
        <el-table :data="form.dealPaymentBeneficiaryList" border>
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('收款方名称')" align="center" min-width="230">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('收款方名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealPaymentBeneficiaryList.' + scope.$index + '.payeeName'" :rules="dealPaymentBeneficiaryRules.payeeName">
                <el-autocomplete
                  v-model="scope.row.payeeName"
                  popper-class="my-autocomplete"
                  :fetch-suggestions="querySearch"
                  :maxlength="100"
                  :placeholder="$t('收款方名称')"
                  @select="handleSelect($event, scope.$index)"
                >
                  <i slot="suffix" class="el-icon-edit" @click="handleIconClick">.</i>
                  <template slot-scope="{ item }">
                    <div class="name">{{ item.value }}</div>
                    <span class="addr">{{ item.address }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('开户行名称')" align="center" min-width="230">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('开户行名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealPaymentBeneficiaryList.' + scope.$index + '.depositBank'" :rules="dealPaymentBeneficiaryRules.depositBank">
                <el-input v-model="scope.row.depositBank" :maxlength="100" :placeholder="$t('开户行名称')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('账户名称')" align="center" min-width="230">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('账户名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealPaymentBeneficiaryList.' + scope.$index + '.accountTitle'" :rules="dealPaymentBeneficiaryRules.accountTitle">
                <el-input v-model="scope.row.accountTitle" :maxlength="100" :placeholder="$t('账户名称')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('银行账号')" align="center" min-width="230">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('银行账号') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealPaymentBeneficiaryList.' + scope.$index + '.bankNumber'" :rules="dealPaymentBeneficiaryRules.bankNumber">
                <el-input v-model="scope.row.bankNumber" :maxlength="25" :placeholder="$t('银行账号')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('收款方地址')" align="center" min-width="230">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('收款方地址') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealPaymentBeneficiaryList.' + scope.$index + '.addressReceiver'" :rules="dealPaymentBeneficiaryRules.addressReceiver">
                <el-input v-model="scope.row.addressReceiver" :maxlength="100" :placeholder="$t('收款方地址')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center" min-width="230">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('备注') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealPaymentBeneficiaryList.' + scope.$index + '.remark'" :rules="dealPaymentBeneficiaryRules.remark">
                <el-input v-model="scope.row.remark" :maxlength="200" :placeholder="$t('备注')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" fixed="right" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:payment:remove']" size="small" type="text" icon="el-icon-delete" @click="delBeneficiary(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addBeneficiary">{{ $t("添加") }}</el-button>
        </div>
        <div class="area-header" style="margin-top: 15px;">
          <span class="area-header-title">{{ $t('划款主体') }}</span>
        </div>
        <el-table
          v-loading="loadContractSubjectLoading"
          :data="form.investorList"
          border
          class="nowrapTable formTable"
          :summary-method="getSummaries"
          show-summary
        >
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('主体名称')" align="center" min-width="150" max-width="200">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('主体名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'investorList.' + scope.$index + '.investorId'" :rules="investorListRules.investorId">
                <el-select v-model="scope.row.investorId" :placeholder="mainBodyListOfCurrentProject.length <= 0 ? $t('请先添加主体') : $t('请选择')" @change="getThisInvestorCurrency($event, scope.$index)">
                  <el-option
                    v-for="dict in mainBodyListOfCurrentProject"
                    :key="dict.investorId + new Date().getTime()"
                    :label="$t(dict.investorName)"
                    :value="dict.investorId"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('收款方')" align="center" min-width="150" max-width="200">
            <template slot="header" slot-scope="{}">
              <!--<i style="color: #ff4949;margin-right: 4px;">*</i>-->
              <span>{{ $t('收款方') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'investorList.' + scope.$index + '.payee'" :rules="investorListRules.payee">
                <el-select v-model="scope.row.payee" :placeholder="$t('收款方')">
                  <el-option
                    v-for="dict in dealPaymentBeneficiaryOption"
                    :key="dict.payeeName + new Date().getTime()"
                    :label="$t(dict.payeeName)"
                    :value="dict.payeeName"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <!--        <el-table-column :label="$t('SPV')" align="center" min-width="150px" max-width="200px">-->
          <!--          <template slot="header" slot-scope="{}">-->
          <!--            <span>{{ $t('SPV') }}</span>-->
          <!--          </template>-->
          <!--          <template slot-scope="scope">-->
          <!--            <el-form-item :prop="'investorList.' + scope.$index + '.spvId'" :rules="investorListRules.spvId">-->
          <!--              <spv-select v-model="scope.row.spvId" />-->
          <!--            </el-form-item>-->
          <!--          </template>-->
          <!--        </el-table-column>-->
          <!--department 部门-->
          <!--
        <el-table-column :label="承担部门" align="center">
          <template slot="header" slot-scope="{}">
            <span>部门</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'investorList.' + scope.$index + '.department'" :rules="investorListRules.department">
              <DeptSelect v-model="scope.row.department" />
            </el-form-item>
          </template>
        </el-table-column>
        -->
          <el-table-column align="center" width="240">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('划款金额') + $t('金额单位') }} {{ contractCurrencyText }}</span>
              <el-tooltip :content="$t('合同中拟定的币种')">
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'investorList.' + scope.$index + '.amount'" :rules="investorListRules.amount">
                <Money v-model="scope.row.amount" unit="w" @change="percentageCalculation($event, scope.$index); rateAmountCalculate(scope.row.amount, scope.row.exchangeRate, scope.$index, true); getExchangeRate(scope.row.amount, scope.row.rateAmount, scope.row.exchangeRate, scope.$index)" />
                <div v-show="scope.row.amountMark === 'show'" style="color: #ffa600;" class="el-form-item__error">{{ $t('警告: 大于未划款金额') }}</div>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="isShowRate" align="center" :width="170">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('汇率') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'investorList.' + scope.$index + '.exchangeRate'" :rules="investorListRules.exchangeRate">
                <el-input-number
                  v-model="scope.row.exchangeRate"
                  :max="999999999"
                  :min="0"
                  :precision="6"
                  :placeholder="scope.row.placeholder"
                  :controls="false"
                  @blur="rateAmountCalculate(scope.row.amount, scope.row.exchangeRate, scope.$index, true)"
                  @change="rateAmountCalculate(scope.row.amount, scope.row.exchangeRate, scope.$index, true)"
                />
                <el-tooltip :content="$t('使用') + scope.row.placeholder" placement="right">
                  <el-button
                    v-if="scope.row.placeholder !== undefined && scope.row.placeholder !== null && scope.row.placeholder !== ''"
                    class="el-icon-document-copy"
                    size="small"
                    type="text"
                    style="color: rgb(143 143 143) !important;cursor: pointer;position: absolute;float: right;right: 0;font-size: 16px;"
                    @click="inputPlaceholder(scope.$index, scope.row.placeholder)"
                  />
                </el-tooltip>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="isShowRate" :label="$t('主体币种')" align="center" :width="150">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('主体币种') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'investorList.' + scope.$index + '.currency'" :rules="investorListRules.currency">
                <el-select v-model="scope.row.currency" :disabled="true">
                  <el-option
                    v-for="dict in currencyOptions"
                    :key="dict.id + new Date().getTime()"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="isShowRate" align="center" :width="150">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('主体划款金额') + $t('金额单位') }}</span>
              <el-tooltip :content="$t('1.划款金额 x 汇率 = 主体划款金额, 2.(汇率为空时)主体划款金额 / 划款金额 = 汇率')">
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'investorList.' + scope.$index + '.rateAmount'" :rules="investorListRules.rateAmount">
                <Money v-model="scope.row.rateAmount" :unit="'w'" :placeholder="$t('主体划款金额')" @change="getExchangeRate(scope.row.amount, scope.row.rateAmount, scope.row.exchangeRate, scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <!--
        <el-table-column align="center" :width="150">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('项目币种汇率') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'investorList.' + scope.$index + '.dealCurrencyRate'" :rules="investorListRules.dealCurrencyRate">
              <el-input-number
                v-model="scope.row.dealCurrencyRate"
                :max="999999999"
                :min="0"
                :precision="6"
                :controls="false"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" :width="150">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('项目币种划款金额') + $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'investorList.' + scope.$index + '.dealCurrencyAmount'" :rules="investorListRules.dealCurrencyAmount">
              <Money v-model="scope.row.dealCurrencyAmount" :unit="'w'" :placeholder="$t('项目币种划款金额')" />
            </el-form-item>
          </template>
        </el-table-column>
        -->
          <el-table-column :label="$t('本次划款占比(%)')" align="center" :width="150">
            <template slot="header" slot-scope="{}">
              <!-- <i style="color: #ff4949;margin-right: 4px;">*</i>-->
              <span>{{ $t('本次划款占比(%)') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'investorList.' + scope.$index + '.ratio'" :rules="investorListRules.ratio">
                <Ratio v-model="scope.row.ratio" disabled />
              </el-form-item>
            </template>
          </el-table-column>
          <!--
        <el-table-column :label="$t('备注')" align="center" width="100px">
          <template slot-scope="scope">
            <el-form-item prop="remark">
              <el-input v-model="scope.row.remark" :maxlength="100" />
            </el-form-item>
          </template>
        </el-table-column>
        -->
          <el-row v-if="form.payCompletionTime !== null && form.payCompletionTime !== '' && form.payCompletionTime !== undefined">
            <!--
          <el-table-column :label="$t('实际划款时间')" align="center" min-width="120px">
            <template slot-scope="scope">
              <el-form-item>
                <el-form-item>
                  <DatePicker v-model="scope.row.actualPaymentTime" :placeholder="$t('实际划款时间')" />
                </el-form-item>
              </el-form-item>
            </template>
          </el-table-column>
          -->
            <el-table-column :label="$t('实际划款金额') + $t('金额单位')" align="center" width="150px">
              <template slot-scope="scope">
                <Money v-model="scope.row.actualPaymentMoney" unit="w" :disabled="true" />
              </template>
            </el-table-column>
          </el-row>
          <el-table-column v-if="!otherBtnHide" fixed="right" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:payment:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div class="tol">
          <el-button v-if="!otherBtnHide" type="primary" icon="el-icon-plus" size="mini" @click="addPayment">{{ $t("添加") }}</el-button>
          <el-button
            v-if="form.actStatus === 'W' || actTaskShowTimeBtn"
            v-hasPermi="['deal:payment:maintain']"
            type="primary"
            size="mini"
            style="z-index: 2100;position: relative;"
            @click="updatePayTimeBtn(form)"
          >{{ $t("维护划款信息") }}</el-button>
        </div>
        <!-- 附件列表 -->
        <FileTable :list.sync="form.fileList" data-type="deal_payment" :business-id="thisDealId" :btn-show="!otherBtnHide" />

        <!--收划款计划-->
        <div v-show="dealContractPayColName === '划款'" v-loading="dealContractPaymentLoading" style="margin-top:15px;">
          <div class="area-header">
            <span class="area-header-title">{{ $t('划款计划') }}</span>
          </div>
          <el-table :data="dealContractPlanList" border class="nowrapTable formTable">
            <el-table-column :label="$t('主体名称')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('主体名称') }}</span>
              </template>
              <template slot-scope="scope">
                {{ scope.row.investName }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计划款时间')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('预计划款时间') }}</span>
              </template>
              <template slot-scope="scope">
                {{ parseTime(scope.row.paymentTime) }}
                <span v-for="time in scope.row.paymentTimeArr" :key="time + new Date().getTime()"> / {{ parseTime(time) }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计划款金额') + $t('金额单位')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('预计划款金额') }}{{ $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                {{ moneyFormat(scope.row.paymentMoney, 'w') }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('未划款金额') + $t('金额单位')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('未划款金额') }}{{ $t('金额单位') }}</span>
                <el-tooltip :content="$t('当前合同: 预计付款金额 - 已付款金额')">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                {{ moneyFormat(scope.row.balance, 'w') }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('币种')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('币种') }}</span>
              </template>
              <template slot-scope="scope">
                {{ currencyFormat(scope.row.currency) }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('备注')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('备注') }}</span>
              </template>
              <template slot-scope="scope">
                {{ scope.row.remark }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-show="dealContractPayColName === '收款'" v-loading="dealContractPaymentLoading" style="margin-top:15px;">
          <div class="area-header">
            <span class="area-header-title">{{ $t('收款计划') }}</span>
          </div>
          <el-table :data="dealContractPlanList" border class="nowrapTable formTable">
            <el-table-column :label="$t('主体名称')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('主体名称') }}</span>
              </template>
              <template slot-scope="scope">
                {{ scope.row.investName }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计收款时间')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('预计收款时间') }}</span>
              </template>
              <template slot-scope="scope">
                {{ parseTime(scope.row.collectionTime) }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计收款金额') + $t('金额单位')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('预计收款金额') }}{{ $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                {{ moneyFormat(scope.row.collectionMoney, 'w') }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('可分配金额') + $t('金额单位')" align="center">
              <template slot="header" slot-scope="{}">

                <span>{{ $t('可分配金额') }}{{ $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                {{ moneyFormat(scope.row.balance, 'w') }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('币种')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('币种') }}</span>
              </template>
              <template slot-scope="scope">
                {{ currencyFormat(scope.row.currency) }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('备注')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('备注') }}</span>
              </template>
              <template slot-scope="scope">
                {{ scope.row.remark }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div v-if="formList instanceof Array && formList.length > 0" id="print" ref="print" style="display: none;">
        <PageForm :form-list="formList" :model="form" />
      </div>
    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <FormBtn v-if="useProcess" ref="formBtn" :btn-hide="btnHide" :bus-data="form" has-permi="deal:payment" :menu-key="menuKey" />
      <!--保存，保存并启动流程，取消 三个按钮-->
      <div v-else>
        <SaveBtn v-if="!btnHide" has-permi="deal:payment" />
      </div>
    </div>
    <!-- 查看合同流程 -->
    <el-dialog :visible.sync="contractPageLoading" :title="$t('合同详情')" :destroy-on-close="true" custom-class="dialogForm" style=" text-align: left;" append-to-body :close-on-click-modal="false" :lock-scroll="false">
      <ProcessInfoForm ref="processInfoForm" />
    </el-dialog>

    <!-- 合同表单-->
    <el-dialog :visible.sync="contractView" :title="$t('合同详情')" :destroy-on-close="true" custom-class="dialogForm" style=" text-align: left;" append-to-body :close-on-click-modal="false" :lock-scroll="false">
      <dealContractForm ref="dealContractForm" />
    </el-dialog>
    <!-- 实际划款信息 -->
    <el-dialog
      :visible.sync="MaintainPaymentInforLoading"
      :title="$t('维护划款信息')"
      :destroy-on-close="true"
      custom-class="dialogForm"
      append-to-body
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <MaintainPaymentInfor ref="MaintainPaymentInfor" :act-title="MaintainPaymentInforTitle" @updatePayTimeSuccess="updatePayTimeSuccess" />
    </el-dialog>

    <!-- 收款方历史 -->
    <el-dialog :visible.sync="oaPayeeHistoryOpen" :title="$t('收款方历史')" :destroy-on-close="true" custom-class="folderOpen" style=" text-align: left;" append-to-body :close-on-click-modal="false" :lock-scroll="false" :closed="restaurants = loadAll()">
      <oaPayeeHistoryList ref="oaPayeeHistoryList" />
    </el-dialog>
  </div>
</template>

<script>
  import { getWebRate, listDealInvestmentAll } from '@/api/deal/investment/dealInvestment.js'
  import { saveDealPayment, getDealPayment, deleteDealPaymentDetail, updatePayTime, getTheRemainingAmount, fallback } from '@/api/deal/payment/dealPayment'
  import { findActIdByContractId, getDealContract, getDealContractPlanByMainId } from '@/api/deal/contract/dealContract'
  import { findActIdByContractIdBf, getDealContractPlanByMainIdBf } from '@/api/bf/contract/bfContract'
  import { getDealContractDebt } from '@/api/deal/contract/debt/dealContractDebt'
  import { fdSubjectSelectByType } from '@/api/fd/config/fdSubjects'
  import ProcessInfoForm from '@/views/act/process/processInfoForm'
  import MaintainPaymentInfor from '@/components/MaintainPaymentInfor'
  import { getPayeeHistory } from '@/api/oa/payment/oaPayment'
  import { getDealBase, getDealName } from '@/api/base/deal/dealBase'
  import { moneyFormat, ruoyiFloat } from '@/utils/ruoyi'
  import { getLpViewByMainBodyId, listDataContract } from '@/api/oa/contract/oaContract'
  import { queryOaAndDealContractById, listDataContractAndChange, findMainBodyByContractId } from '@/api/deal/contract/dealContract.js'
  import MainBodySelect from '@/components/MainBodySelect'
  // import SpvSelect from '@/components/Select/SpvSelect'
  import dealContractForm from '@/views/deal/contract/dealContractForm.vue'
  import oaPayeeHistoryList from '@/views/oa/payment/oaPaymentHistoryList.vue'
  import { getMenuProcess } from '@/api/act/process/wfMenuProcess'
  export default {
    components: {
      ProcessInfoForm,
      MaintainPaymentInfor,
      // SpvSelect,
      MainBodySelect,
      dealContractForm,
      oaPayeeHistoryList
    },
    data() {
      /** 校验划款金额是否超过合同金额  */
      const checkTotal = (rule, value, callback) => {
        if (value === undefined || value === '' || value === null || value === 0) {
          callback(new Error(this.$t('必填信息')))
        }
        if (parseFloat(this.form.total) > parseFloat(this.form[this.contractType]) && (parseFloat(this.form[this.contractType]) > 0)) {
          if (this.thisDealId) {
            callback(new Error(this.contractType === 'contractAmount' ? this.$t('不能超过合同金额') : this.$t('不能超过合同应划款金额')))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      /**
       * 划款主体校验是否存在重复
       * @param rule
       * @param value
       * @param callback
       */
      const checkInvestor = (rule, value, callback) => {
        if (value === undefined || value === '' || value === null) {
          callback(new Error(this.$t('必填信息')))
        } else {
          const investList = this.form.investorList
          if (investList === null || investList === undefined) {
            callback()
          } else {
            var count = 0
            investList.forEach(item => {
              if (item.investorId === value) {
                count++
              }
            })
            // 校验重复
            if (count > 1) {
              // callback(new Error(this.$t('主体不可重复')))
              callback()
            } else {
              callback()
            }
            // 给列表里添加上type
            if (this.mainBodyListOfCurrentProject) {
              const indexInt = parseInt(rule.field.substring(rule.field.indexOf('.') + 1, rule.field.lastIndexOf('.')))
              this.mainBodyListOfCurrentProject.forEach(item => {
                if (item.investorId === value) {
                  this.form.investorList[indexInt].type = item.investorType
                }
              })
            }
          }
        }
      }
      const checkCurrencyByInvestor = (rule, value, callback) => {
        if (value !== undefined && value !== '' && value !== null) {
          const index = parseInt(rule.field.substring(rule.field.indexOf('.') + 1, rule.field.lastIndexOf('.')))
          if (this.form.investorList) {
            if (this.form.investorList[index].currency === this.contractCurrency && value !== 1) {
              this.msgWarning(this.$t('相同币种汇率必须为 1 '))
              this.form.investorList[index].exchangeRate = 1
              this.form.investorList[index].rateAmount = this.form.investorList[index].amount
              this.rateAmountCalculate(this.form.investorList[index].amount, this.form.investorList[index].exchangeRate, index, true)
              callback()
            } else if (this.form.investorList[index].currency === this.contractCurrency && value === 0) {
              callback(new Error(this.$t('汇率不能为0')))
            } else {
              callback()
            }
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      const checkCurrencyByEquity = (rule, value, callback) => {
        if (this.$route.query.dealType === 'equity') {
          if (value === undefined || value === null || value === '') {
            callback(new Error(this.$t('必填信息')))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      const checkPayeeName = (rule, value, callback) => {
        if (value !== undefined && value !== '' && value !== null) {
          const rowIndex = parseInt(rule.field.substring(rule.field.indexOf('.') + 1, rule.field.lastIndexOf('.')))
          this.form.dealPaymentBeneficiaryList.forEach((item, index) => {
            if (item.payeeName === value && index !== rowIndex) {
              this.msgError(this.$t('不可重复!'))
              item.payeeName = ''
            }
          })
          callback()
        } else {
          callback(new Error(this.$t('必填信息')))
        }
      }
      const checkContractPayables = (rule, value, callback) => {
        console.log('checkContractPayables', value)
        if (value !== undefined && value !== '' && value !== null) {
          callback()
        } else {
          if (this.form.contractPayables !== undefined && this.form.contractPayables !== '' && this.form.contractPayables !== null) {
            callback()
          } else {
            callback(new Error(this.$t('必填信息')))
          }
        }
      }
      // 同一主体不能出现相同收款方
      const checkInvestRepeat = (rule, value, callback) => {
        if (value !== undefined && value !== '' && value !== null) {
          var temp = []
          this.form.investorList && this.form.investorList.forEach(item => {
            if ((item.investorId !== undefined && item.investorId !== null && item.investorId !== '') && (item.payee !== undefined && item.payee !== null && item.payee !== '')) {
              var text = item.investorId + '-' + item.payee
              if (temp.includes(text)) {
                callback(new Error(this.$t('同一主体存在相同的收款方')))
              }
              temp.push(text)
            }
          })
          callback()
        } else {
          callback(new Error(this.$t('必填信息')))
        }
      }
      const checkRequired = (rule, value, callback) => {
        console.log(rule, value)
        if (value !== undefined && value !== '' && value !== null) {
          callback()
        } else {
          callback(new Error(this.$t('必填信息')))
        }
      }
      return {
        // 菜单标识
        menuKey: 'deal_payment',
        // 是否配置了流程
        useProcess: false,
        // 部门树选项
        deptOptions: undefined,
        subDisabled: true,
        loading: false,
        previewId: '',
        parameters: '',
        // 是否隐藏保存按钮
        btnHide: false,
        // 是否隐藏其它按钮
        otherBtnHide: false,
        // 划款大类
        typeOptions: [],
        typeOptionsDetails: [],
        selectID: '',
        // 流程审批页面是否展示维护付款时间页面
        actTaskShowTimeBtn: false,
        // 表单参数
        form: {
          // 划款主体
          investorList: [],
          // 附件列表
          fileList: [],
          expenseEntityType1: [],
          expenseEntityType: []
        },
        // 表单校验
        rules: {
          applyUser: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
          applyTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
          currency: [{ required: true, validator: checkCurrencyByEquity,	trigger: 'blur' }],
          typeSub: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
          method: [{ required: false, message: this.$t('必填信息'),	trigger: 'blur' }],
          level: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
          center: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
          total: [{ required: true, validator: checkTotal,	trigger: ['blur', 'change'] }],
          actTitle: [{ required: true, validator: checkRequired, trigger: 'blur' }],
          contractPayables: [{ required: true, validator: checkContractPayables, trigger: ['change', 'blur'] }],
          contractId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
          meetPrerequisites: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
        },
        investorListRules: {
          type: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
          investorId: [{ required: true, validator: checkInvestor, trigger: ['blur', 'change'] }, { validator: checkInvestRepeat }],
          // payee: [{ required: true, validator: checkInvestRepeat, trigger: ['blur', 'change'] }],
          amount: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
          exchangeRate: [{ required: true, validator: checkCurrencyByInvestor,	trigger: ['blur', 'change'] }],
          dealCurrencyAmount: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
          dealCurrencyRate: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }]
        },
        dealPaymentBeneficiaryRules: {
          payeeName: [{ required: true, validator: checkPayeeName,	trigger: ['blur', 'change'] }]
        },
        typtId: '',
        // 划款方式
        methodOptions: [],
        // 紧急级别
        levelOptions: [],
        // 划款大类
        typeMainOption: [],
        // 合同下拉
        contractOptions: [],
        // dealId
        thisDealId: undefined,
        restaurants: [],
        dealContractPlanList: [],
        dealContractPaymentLoading: false,
        dealContractPayColName: '收付款',
        contractPageLoading: false,
        contractView: false,
        // 划款主体遮盖层
        loadContractSubjectLoading: false,
        MaintainPaymentInforLoading: false,
        MaintainPaymentInforTitle: '',
        thisPageContractId: '',
        // 当前项目主体列表
        mainBodyListOfCurrentProject: [],
        // 划款先决条件
        paymentPrerequisites: '',
        paymentPrerequisitesShow: false,
        oaPayeeHistoryOpen: false,
        currencyOptions: [],
        contractCurrency: '',
        contractCurrencyText: '',
        dealPaymentBeneficiaryOption: [],
        contractType: 'contractAmount',
        dealBaseData: undefined,
        // 是否展示汇率字段
        isShowRate: false,
        // 来自流程中
        processPhaseActTitle: undefined,
        formList: []
      }
    },
    computed: {

    },
    watch: {
      // fdSubjectSelectByType: function() {
      //   this.form = this.dealPaymentData
      // }
      contractCurrency: {
        handler(val) {
          if (val) {
            this.contractCurrencyText = ' - (' + this.formatCurrency(val) + ')'
          } else {
            this.contractCurrencyText = ''
          }
        },
        deep: true
      },
      'form.dealPaymentBeneficiaryList': {
        handler(val) {
          this.dealPaymentBeneficiaryOption = []
          if (val) {
            val.forEach(item => {
              if (item.payeeName) {
                this.dealPaymentBeneficiaryOption.push(item)
              }
            })
            this.autoInputPayInfo()
          }
        },
        deep: true,
        immediate: true
      },
      'form.investorList': {
        handler() {
          this.refreshDisplayExchangeRate()
        },
        deep: true,
        immediate: true
      }
    },
    mounted() {
      this.restaurants = this.loadAll()
    },
    created() {
      // 划款方式
      this.getDicts('oa_payment_method').then(response => {
        this.methodOptions = response.data
      })
      // 紧急级别
      this.getDicts('oa_level_emergency').then(response => {
        this.levelOptions = response.data
      })
      this.getDicts('currency').then(response => {
        this.currencyOptions = response.data
      })
      // 划款类型
      fdSubjectSelectByType('deal', 'oa_payment').then(response => {
        this.typeMainOption = response.data
      })
      getMenuProcess(this.menuKey).then(response => {
        this.useProcess = (response.data !== undefined && response.data !== null && response.data !== '')
      })
      this.$bus.$emit('async_done')
    },
    methods: {
      fallback() {
        return new Promise((resolve, reject) => {
          fallback(this.form.id).then(response => {
            if (response.data === 1 && response.code === 200) {
              this.msgSuccess(this.$t('操作成功'))
              resolve()
            } else {
              this.msgError(this.$t('操作失败'))
              reject()
            }
          }).catch(() => {
            this.msgError(this.$t('操作失败'))
            reject()
          })
        })
      },
      // 币种字典翻译
      currencyFormat(value) {
        return this.selectDictLabel(this.currencyOptions, value)
      },
      // 添加划款主体
      addPayment() {
        if (this.form.contractId === '' || this.form.contractId === undefined || this.form.contractId === null) {
          this.msgError(this.$t('请先选择合同!'))
        } else {
          const row = {
            id: undefined,
            type: '',
            investorId: '',
            spvId: '',
            amount: 0,
            rateAmount: undefined,
            rate: undefined,
            ratio: '',
            payee: '',
            remark: ''
          }
          if (!(this.form.investorList instanceof Array)) {
            this.$set(this.form, 'investorList', [])
          }
          this.$nextTick(() => {
            this.form.investorList.push(row)
            this.changeInvestLength()
          })
        }
      },
      // 添加收款方信息
      addBeneficiary() {
        if (this.form.contractId === '' || this.form.contractId === undefined || this.form.contractId === null) {
          this.msgError(this.$t('请先选择合同!'))
        } else {
          const row = {
            id: undefined,
            payeeName: '',
            depositBank: '',
            accountTitle: '',
            bankNumber: '',
            addressReceiver: '',
            remark: ''
          }
          if (!(this.form.dealPaymentBeneficiaryList instanceof Array)) {
            this.$set(this.form, 'dealPaymentBeneficiaryList', [])
          }
          this.$nextTick(() => {
            this.form.dealPaymentBeneficiaryList.push(row)
          })
        }
      },
      delBeneficiary(index, row) {
        if (this.form.investorList) {
          this.form.investorList.forEach(item => {
            if (item.payee === row.payeeName) {
              item.payee = ''
            }
          })
        }
        this.form.dealPaymentBeneficiaryList.splice(index, 1)
      },
      // 删除划款主体
      delHandle(index, row) {
        const id = row.id
        if (id !== undefined && id !== '' && id != null) {
          this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          })
            .then(function() {
              return deleteDealPaymentDetail(id)
            }).then(() => {
            this.form.investorList.splice(index, 1)
            this.changeInvestLength()
            return this.msgSuccess(this.$t('删除成功'))
          })
            .catch(function() {})
        } else {
          this.form.investorList.splice(index, 1)
          this.changeInvestLength()
        }
      },
      // 计算报销总额
      getSummaries() {
        let sum = 0
        this.form.investorList.forEach(item => {
          sum += +item.amount
        })
        this.$set(this.form, 'total', sum !== 0 ? sum : undefined)
        return sum
      },
      // 初始化数据
      init(data) {
        this.loading = true
        this.dealContractPayColName = ''
        this.mainBodyListOfCurrentProject = []
        if (data != null && data.id !== undefined && data.id !== '' && data.id !== null) {
          getDealPayment(data.id).then(response => {
            this.form = response.data
            if (this.$route.query.id === null || this.$route.query.id === '' || this.$route.query.id === undefined) {
              this.thisDealId = this.form.dealId
            } else {
              this.thisDealId = this.$route.query.id
            }
            this.thisPageContractId = this.form.contractId
            // 加载项目主体都有哪些
            listDealInvestmentAll({ dealId: (this.isEmpty(this.thisDealId) ? '-1' : this.thisDealId) }).then(response => {
              response.data.forEach(item => {
                this.mainBodyListOfCurrentProject.push(item)
              })
            })
            // 加载合同
            this.contractDict()
            // 加载合同金额
            this.getContractMoney()
            // 加载合同下的收划款计划
            this.getContractChange(this.form.contractId)
            // 获取该和同的币种
            this.getContractCurrency(this.form.contractId, () => {})
            // 流程审批页面展示收付款计划
            this.checkActTaskShowTimeBtn(data)
            getDealBase(this.thisDealId).then(response => {
              this.dealBaseData = response.data
              setTimeout(() => {
                // 刷新是否展示多币种
                this.refreshDisplayExchangeRate()
              }, 1500)
            })
            this.loading = false
            this.loadForm()
          })
        } else {
          this.processPhaseActTitle = JSON.parse(JSON.stringify((!this.isEmpty(data) && !this.isEmpty(data.actTitle)) ? data.actTitle : ''))
          this.reset()
          if (this.processPhaseActTitle !== '') {
            this.form.actTitle = this.processPhaseActTitle
          }
          // 默认带出流程中必须要传的附件
          if (data !== null && data !== undefined) {
            this.form.fileList = data.fileList
          }
          this.thisDealId = this.$route.query.id
          // 加载合同
          this.contractDict()
          // 默认加载出 划款主体. 主体内容是项目主体中的所有主体
          this.findListInvestor()
          getDealBase(this.$route.query.id).then(response => {
            this.dealBaseData = response.data
          })
          this.loading = false
        }
      },
      loadForm() {
        this.$nextTick(() => {
          this.formList = [
            { title: '申请单', value: 'input', type: 'table',
              tablePageList: [
                { title: '项目名称', type: 'title', vIf: !this.$route.query.id },
                { title: '项目名称', value: 'dealId', type: 'input', width: '75%', vIf: !this.$route.query.id },
                { title: '申请标题', type: 'title' },
                { title: '申请标题', value: 'actTitle', type: 'textarea', width: '75%' },
                { title: '申请人', type: 'title' },
                { title: '申请人', value: 'applyUser', type: 'user', userMultiple: false },
                { title: '申请时间', type: 'title' },
                { title: '申请时间', value: 'applyTime', type: 'time' },
                { title: '划款类型', type: 'title' },
                { title: '划款类型', value: 'typeSub', type: 'select', selectType: 'options', selectDataList: this.typeMainOption, selectLabelParams: 'dictLabel', selectValueParams: 'dictValue' },
                // { title: '币种', type: 'title' },
                // { title: '币种', value: 'currency', type: 'select', selectType: 'dict', dictVal: 'currency' },
                { title: '关联合同', type: 'title' },
                { title: '关联合同', value: 'contractId', type: 'select', selectType: 'options', selectDataList: this.contractOptions, selectLabelParams: 'name', selectValueParams: 'id' },
                // { title: '划款方式', type: 'title' },
                // { title: '划款方式', value: 'method', type: 'select', selectType: 'options', selectDataList: this.methodOptions, selectLabelParams: 'dictLabel', selectValueParams: 'dictValue' },
                { title: '紧急级别', type: 'title' },
                { title: '紧急级别', value: 'level', type: 'select', selectType: 'options', selectDataList: this.levelOptions, selectLabelParams: 'dictLabel', selectValueParams: 'dictValue' },
                { title: '是否满足先决条件', type: 'title', vIf: !!((this.form.contractId && this.form.contractAmount !== 0 && this.form.contractAmount !== undefined && this.form.contractAmount !== null)) },
                { title: '是否满足先决条件', value: 'meetPrerequisites', type: 'select', selectType: 'dict', dictVal: 'deal_satisfaction_status', vIf: !!((this.form.contractId && this.form.contractAmount !== 0 && this.form.contractAmount !== undefined && this.form.contractAmount !== null)) },
                { title: '合同金额(万)', type: 'title', vIf: !!((this.form.contractId && this.form.contractAmount !== 0 && this.form.contractAmount !== undefined && this.form.contractAmount !== null)) },
                { title: '合同金额(万)', value: 'contractAmount', type: 'money', moneyUnit: 'w', vIf: !!((this.form.contractId && this.form.contractAmount !== 0 && this.form.contractAmount !== undefined && this.form.contractAmount !== null)) },
                { title: '合同应划款金额(万)', type: 'title', vIf: this.contractType === 'contractPayables' },
                { title: '合同应划款金额(万)', value: 'contractPayables', type: 'money', moneyUnit: 'w', vIf: this.contractType === 'contractPayables' },
                { title: '划款金额(万)', type: 'title', vIf: this.form.contractId },
                { title: '划款金额(万)', value: 'total', type: 'money', moneyUnit: 'w', vIf: this.form.contractId },
                // { title: '本次划款金额(万)', type: 'title' },
                // { title: '本次划款金额(万)', value: 'total', type: 'amountOfThisPayment', moneyUnit: 'w' },
                { title: '划款先决条件', type: 'title', vIf: !!((this.form.contractId && this.paymentPrerequisitesShow === true)) },
                { title: '划款先决条件', value: 'paymentPrerequisites', type: 'textarea', width: '75%', vIf: !!((this.form.contractId && this.paymentPrerequisitesShow === true)) },
                { title: '备注', type: 'title' },
                { title: '备注', value: 'remark', type: 'textarea', width: '75%' }
              ]
            },
            { title: '收款方信息', value: 'dealPaymentBeneficiaryList', type: 'dataList', listType: 'vertical',
              vIf: this.form.dealPaymentBeneficiaryList.length > 0,
              listPageList: [
                { title: '收款方名称', value: 'payeeName' },
                { title: '开户行名称', value: 'depositBank' },
                { title: '账户名称', value: 'accountTitle' },
                { title: '银行账号', value: 'bankNumber' },
                { title: '收款方地址', value: 'addressReceiver' },
                { title: '备注', value: 'remark' }
              ]
            },
            { title: '划款主体', value: 'investorList', type: 'dataList', listType: 'vertical',
              vIf: this.form.investorList.length > 0,
              listPageList: [
                { title: '主体名称', value: 'investorId', type: 'select', selectType: 'options', selectDataList: this.mainBodyListOfCurrentProject, selectLabelParams: 'investorName', selectValueParams: 'investorId' },
                { title: '收款方', value: 'payee', type: 'select', selectType: 'options', selectDataList: this.dealPaymentBeneficiaryOption, selectLabelParams: 'payeeName', selectValueParams: 'payeeName' },
                { title: '划款金额(万)', value: 'amount', type: 'money', moneyUnit: 'w' },
                { title: '汇率', value: 'exchangeRate', vIf: this.isShowRate === true },
                { title: '主体币种', value: 'currency', type: 'select', selectType: 'options', selectDataList: this.currencyOptions, selectLabelParams: 'dictLabel', selectValueParams: 'dictValue', vIf: this.isShowRate === true },
                { title: '主体划款金额(万)', value: 'rateAmount', type: 'money', moneyUnit: 'w', vIf: this.isShowRate === true },
                { title: '本次划款占比(%)', value: 'ratio' },
                { title: '实际划款金额(万)', value: 'actualPaymentMoney', type: 'money', moneyUnit: 'w', vIf: this.form.payCompletionTime !== null && this.form.payCompletionTime !== '' && this.form.payCompletionTime !== undefined }
              ]
            },
            { title: '附件信息', value: 'fileList', type: 'fileList', listType: 'vertical',
              vIf: this.form.fileList.length > 0,
              listPageList: [
                { title: '文件分类', value: 'directoryName' },
                { title: '附件名称', value: 'name' },
                { title: '备注', value: 'remark' },
                { title: '上传人', value: 'updateBy', childrenValue: 'nickName' },
                { title: '上传时间', value: 'createTime' }
              ]
            },
            { title: '划款计划', value: 'dealContractPlanList', type: 'dataList', listType: 'vertical',
              vIf: !!((this.form.dealContractPlanList && this.form.dealContractPlanList.length > 0 && this.dealContractPayColName === '划款')),
              listPageList: [
                { title: '主体名称', value: 'investName' },
                { title: '预计划款时间', value: 'paymentTime', type: 'time' },
                { title: '预计划款金额(万)', value: 'paymentMoney', type: 'money', moneyUnit: 'w' },
                { title: '未划款金额(万)', value: 'balance', type: 'money', moneyUnit: 'w' },
                { title: '币种', value: 'currency', type: 'select', selectType: 'options', selectDataList: this.currencyOptions, selectLabelParams: 'dictLabel', selectValueParams: 'dictValue' },
                { title: '备注', value: 'remark' }
              ]
            },
            { title: '收款计划', value: 'dealContractPlanList', type: 'dataList', listType: 'vertical',
              vIf: !!((this.form.dealContractPlanList && this.form.dealContractPlanList.length > 0 && this.dealContractPayColName === '收款')),
              listPageList: [
                { title: '主体名称', value: 'investName' },
                { title: '预计收款时间', value: 'collectionTime', type: 'time' },
                { title: '预计收款金额(万)', value: 'collectionMoney', type: 'money', moneyUnit: 'w' },
                { title: '可分配金额(万)', value: 'balance', type: 'money', moneyUnit: 'w' },
                { title: '币种', value: 'currency', type: 'select', selectType: 'options', selectDataList: this.currencyOptions, selectLabelParams: 'dictLabel', selectValueParams: 'dictValue' },
                { title: '备注', value: 'remark' }
              ]
            }
          ]
        })
      },
      actTitleInput(val) {
        this.$set(this.form, 'actTitle', val)
        this.$forceUpdate()
      },
      changeDeal() {
        this.thisDealId = this.form.dealId
        this.contractDict()
        this.findListInvestor()
        getDealBase(this.thisDealId).then(response => {
          this.dealBaseData = response.data
        })
      },
      // 合同
      contractDict() {
        var tempDealId = this.form.dealId
        if (tempDealId === '' || tempDealId === undefined || tempDealId === null) {
          tempDealId = this.$route.query.id
        }
        const params = {
          dealId: tempDealId
        }
        listDataContract(params).then(response => {
          const temp = []
          response.data.forEach(item => {
            if (item.isPayment !== 'no') {
              this.contractOptions.push(item)
              temp.push(item.id)
            }
          })
          if (!temp.includes(this.form.contractId)) {
            listDataContractAndChange(this.form.contractId).then(response => {
              const data = response.data
              if (data !== null) {
                this.contractOptions.push({ id: data.id, name: data.name, type: data.type, contractPayables: data.contractPayables })
              }
            })
          }
          this.loadForm()
          this.showPrivateContractType(this.form.contractId)
        })
      },
      // 默认加载出 划款主体. 主体内容是项目主体中的所有主体
      findListInvestor() {
        // 根据选择的合同加载 对应的主体
        this.form.investorList = []
        this.mainBodyListOfCurrentProject = []
        listDealInvestmentAll({ 'dealId': (this.isEmpty(this.thisDealId) ? '-1' : this.thisDealId) }).then(response => {
          response.data.forEach(item => {
            this.mainBodyListOfCurrentProject.push(item)
          })
          this.addInvestorList(response.data)
        })
      },
      addInvestorList(data) {
        if (data !== null && data !== undefined) {
          data.some(item => {
            const row = {
              id: undefined,
              type: item.investorType,
              investorId: item.investorId,
              spvId: item.spvId,
              currency: item.currency,
              rateAmount: undefined,
              rate: undefined,
              amount: '',
              ratio: '',
              remark: ''
            }
            if (!(this.form.investorList instanceof Array)) {
              this.$set(this.form, 'investorList', [])
            }
            this.$nextTick(() => {
              this.form.investorList.push(row)
              this.changeInvestLength()
            })
          })
        }
        this.loadContractSubjectLoading = false
      },
      inputPlaceholder(index, val) {
        if (val !== undefined && val !== null && val !== '') {
          val = val.replaceAll('汇率参考', '').replaceAll(':', '').trim()
          this.$set(this.form.investorList[index], 'exchangeRate', val)

          // 计算汇率
          const row = this.form.investorList[index]
          this.rateAmountCalculate(row.amount, row.exchangeRate, index, true)
          this.$forceUpdate()
        }
      },
      // 刷新是否展示子表的多币种
      refreshDisplayExchangeRate() {
        this.$nextTick(() => {
          this.isShowRate = false
          this.form.investorList.forEach(item => {
            if (item.currency !== undefined && item.currency !== this.contractCurrency && this.contractCurrency !== undefined && this.contractCurrency !== '') {
              this.isShowRate = true
            }
          })
        })
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          applyUser: this.$store.state.user.userId,
          dealId: this.$route.query.id,
          typeMain: undefined,
          currency: undefined,
          method: '0',
          level: '0',
          total: 0,
          department: undefined,
          typeSub: undefined,
          applyTime: new Date(),
          payeeName: undefined,
          depositBank: undefined,
          accountTitle: undefined,
          bankNumber: undefined,
          addressReceiver: undefined,
          payCompletionTime: undefined,
          contractId: undefined,
          meetPrerequisites: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined,
          remark: undefined,
          atcTitle: undefined,
          investorList: [],
          fileList: [],
          typeMainOption: [],
          dealPaymentBeneficiaryList: []
        }
        this.resetForm('form')
      },
      // 取消按钮
      cancel() {
        this.$parent.$parent.formOpen = false
        this.$parent.$parent.reset()
      },
      // 关闭form页面
      closeForm(type) {
        // 关闭form页面遮罩层
        this.loading = false
        if (type !== 'actSave') {
          // 关闭form页面
          if (this.$parent.$parent.formOpen !== undefined) {
            this.$parent.$parent.formOpen = false
          }
          // 刷新list页面
          if (this.$parent.$parent.getList !== undefined) {
            this.$parent.$parent.getList()
          }
        }
        if (this.$parent.visible !== undefined) {
          this.$parent.visible = false
        }
      },
      /** 提交按钮 */
      submitForm: function(type) {
        return new Promise((resolve, reject) => {
          if (this.form.investorList !== null && this.form.investorList !== undefined) {
            this.form.investorList.forEach(item => {
              item.amount = parseFloat(item.amount)
            })
          }
          this.$refs['form'].validate(valid => {
            if (valid) {
              this.loading = true
              // 给汇率等字段赋值
              if (!this.isShowRate) {
                this.form.investorList.forEach((item, index) => {
                  this.mainBodyListOfCurrentProject && this.mainBodyListOfCurrentProject.forEach(sub => {
                    if (sub.investorId === item.investorId) {
                      this.form.investorList[index].currency = sub.currency
                    }
                  })
                  item.exchangeRate = 1
                  item.rateAmount = item.amount
                })
              }
              // 保存方式，如果值为actSave则是从流程表单中进行的保存，默认将delFlag 设置为2,审批通过后在更新为0
              this.form.saveType = type
              this.form.useProcess = this.useProcess
              saveDealPayment(this.form).then(response => {
                if (response.code === 200) {
                  if (type === 'process') {
                    // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                    this.form.id = response.data.id
                    this.startProcess(response.data)
                  } else {
                    this.msgSuccess(this.$t('保存成功'))
                    this.closeForm(type)
                  }
                  resolve(response.data.id)
                } else {
                  this.msgError(response.msg)
                  this.loading = false
                  reject(response)
                }
              }).catch(() => {
                this.loading = false
              })
            } else {
              this.locationError(document)
              reject()
            }
          })
        })
      },
      // 启动流程
      startProcess: async function(data) {
        this.loading = false
        var dealName = await getDealName(this.$route.query.id || this.form.dealId)
        // 启动流程时候传入的参数
        const processData = {}
        // 待办标题
        processData.title = '「' + dealName + '」' + this.$t('项目划款') + ':' + this.form.actTitle + '  金额:' + moneyFormat(data.total, 'w') + this.$t('金额单位')
        // 业务表名
        processData.dataTable = 'deal_payment'
        // 业务ID
        processData.dataId = data.id
        // 业务表单地址
        processData.formPath = '@/views/deal/payment/dealPaymentForm'
        processData.viewPath = '@/views/deal/payment/dealPaymentView'
        // 菜单标识(根据菜单标识判断的走哪个流程)
        processData.menuKey = this.menuKey
        this.startProcessByMenu(processData, () => {
          this.form.actStatus = 'D'
          this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
          this.closeForm()
        })
      },
      // 流程审批页面展示收付款计划
      checkActTaskShowTimeBtn(data) {
        this.actTaskShowTimeBtn = false
        console.log(data, '获取节点的sid')
        if (data && data.actTaskKey === 'update_pay_time') {
          console.log('展示维护付款时间按钮')
          this.actTaskShowTimeBtn = true
        }
        this.loadForm()
      },
      // -------------------------------------- 收款方空间控件方法 start(无需修改) --------------------------------------
      querySearch(queryString, cb) {
        var restaurants = this.restaurants
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().includes(queryString.toLowerCase()))
        }
      },
      // -------------------------------------- 收款方控件内置方法 end --------------------------------------
      // 收款方历史提示
      loadAll() {
        var temp = []
        getPayeeHistory().then(reponse => {
          if (reponse.data !== null) {
            for (var i = 0; i < reponse.data.length; i++) {
              var obj = {
                'value': reponse.data[i].payeeName,
                'address': reponse.data[i].depositBank + '|' + reponse.data[i].accountTitle + '|' + reponse.data[i].bankNumber
              }
              temp.push(obj)
            }
          }
        })
        return temp
      },
      changeInvestLength() {
        var val = this.form.investorList
        if (!this.isEmpty(this.processPhaseActTitle)) {
          if (val && val.length === 1) {
            if (val[0].investorId) {
              getLpViewByMainBodyId(val[0].investorId).then(response => {
                this.form.actTitle = response.data.short_name + '-' + this.processPhaseActTitle
                this.$forceUpdate()
              })
            }
          } else {
            this.form.actTitle = this.processPhaseActTitle
            this.$forceUpdate()
          }
        }
      },
      // 收款方选择后触发
      handleSelect(rowItem, index) {
        this.form.dealPaymentBeneficiaryList[index].payeeName = rowItem.value
        var arr = rowItem.address.split('|')
        this.form.dealPaymentBeneficiaryList[index].depositBank = arr[0]
        this.form.dealPaymentBeneficiaryList[index].accountTitle = arr[1]
        this.form.dealPaymentBeneficiaryList[index].bankNumber = arr[2]
      },
      // 收款方旁边的小按钮
      handleIconClick() {
        this.oaPayeeHistoryOpen = true
      },
      // 计算划款主体的百分比
      percentageCalculation(value, index) {
        // 合同金额有值 (例如: 投资协议) 计算划款占比方式
        if (this.form[this.contractType]) {
          this.form.investorList.forEach(item => {
            var ratioTemp = (item.amount / this.form[this.contractType]) * 100
            if (isNaN(ratioTemp)) {
              ratioTemp = 0
            }
            if (ratioTemp === '') {
              ratioTemp = 0
            }
            item.ratio = ratioTemp.toFixed(2)
            if (parseFloat(item.ratio) > 100) {
              item.ratio = 100
            }
          })
        } else {
          // 合同金额没值, 例如框架协议. 没有合同金额.  按划款主体总额计算
          var amountSum = 0
          this.form.investorList.forEach(item => {
            if (item.amount === undefined || item.amount === '' || item.amount === null || isNaN(item.amount)) {
              item.amount = 0
            }
            amountSum += parseFloat(item.amount)
          })
          this.form.investorList.forEach(item => {
            var ratioTemp = (item.amount / amountSum) * 100
            if (isNaN(ratioTemp)) {
              ratioTemp = 0
            }
            if (ratioTemp === '') {
              ratioTemp = 0
            }
            item.ratio = ratioTemp.toFixed(2)
            if (parseFloat(item.ratio) > 100) {
              item.ratio = 100
            }
          })
        }
        this.checkInvestAmount(value, index)
      },
      /**
       * .校验 主体中的金额 是否超过划款计划中的金额
       */
      checkInvestAmount(value, indexInt) {
        // 划款金额总额 是否超过 合同金额
        if (this.dealContractPlanList !== undefined && this.dealContractPlanList !== null && this.dealContractPlanList.length > 0) {
          if (this.dealContractPlanList) {
            // 判断划款金额是否超过划款计划金额
            var investorId = this.form.investorList[indexInt].investorId
            var amount = this.form.investorList[indexInt].amount

            // 划款计划中可能存在多个相同主体的情况
            var allPlanArr = []
            this.dealContractPlanList.some(item => {
              if (item.investId === investorId) {
                allPlanArr.push(item)
              }
            })
            var moneySum = 0
            allPlanArr.forEach(item => {
              moneySum += this.formatMoney(item.balance)
            })
            this.form.investorList[indexInt].amountMark = undefined
            if (this.formatMoney(amount) > this.formatMoney(moneySum)) {
              // callback(new Error(this.$t('不能超过划款计划中的预计划款金额')))
              // callback(new Error(this.$t('大于未划款金额')))
              console.log('大于未划款金额')
              this.form.investorList[indexInt].amountMark = 'show'
            }
          }
        }
      },
      formatMoney(val) {
        if (val && val !== '' && !isNaN(parseFloat(val))) {
          return ruoyiFloat().formatNum(val)
        }
        return 0
      },
      contractChange(id) {
        var that = this
        if (this.form !== undefined && this.form.id !== undefined && this.form.id !== null) {
          this.$confirm(this.$t('将会清空主体中的内容,是否继续'), this.$t('提示'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          }).then(() => {
            // 合同金额
            this.getContractMoney()
            // 加载合同下的收划款计划
            that.getContractChange(id)
            // 合同发生变化时带出合同下的主体
            that.getInvestorByContract(id)
            that.thisPageContractId = id
            that.showPrivateContractType(id)
          }).catch(() => {
            that.form.contractId = this.thisPageContractId
          })
          // 获取该合同的币种
          this.getContractCurrency(id, () => {})
        } else {
          // 合同金额
          this.getContractMoney()
          // 加载合同下的收划款计划
          that.getContractChange(id)
          // 合同发生变化时带出合同下的主体
          this.getInvestorByContract(id)
          that.showPrivateContractType(id)
          // 获取该合同的币种
          this.getContractCurrency(id, () => {})
        }
      },
      showPrivateContractType(id) {
        var that = this
        that.contractType = 'contractAmount'
        const object = that.contractOptions.find(obj => obj.id === id)
        if (object) {
          if (object.type === 'KZZTZXY' || object.type === 'KZZXYTZ') {
            that.contractType = 'contractPayables'
            that.contractPayables = (object.contractPayables === undefined || object.contractPayables === null || object.contractPayables === '') ? 0 : object.contractPayables
          }
        }
      },
      /**
       * 获取当前合同的币种
       */
      getContractCurrency(id, callback) {
        getDealContract(id).then(response => {
          this.contractCurrency = response.data.currency
          this.form.currency = this.contractCurrency
          callback()
        })
      },
      // 划款主体列表 修改主体名称时 加载出该主体对应的币种
      getThisInvestorCurrency(investorId, index) {
        console.log('主体: ' + investorId)
        if (this.mainBodyListOfCurrentProject) {
         this.mainBodyListOfCurrentProject.forEach(item => {
           if (item.investorId === investorId) {
             this.form.investorList[index].currency = item.currency
             if (item.currency === this.form.currency) {
               this.form.investorList[index].exchangeRate = 1
             }
           }
         })
        }
        // 刷新是否展示多币种
        this.refreshDisplayExchangeRate()
        this.form.investorList[index].exchangeRate = undefined
        this.loadRate(index)
        this.autoInputPayInfo()
      },
      // 当收款方只有一条时, 自动填写收款方
      autoInputPayInfo() {
        if (this.form.dealPaymentBeneficiaryList && this.form.dealPaymentBeneficiaryList.length === 1) {
          var payeeName = this.form.dealPaymentBeneficiaryList[0].payeeName
          this.form.investorList && this.form.investorList.forEach(item => {
            if (!this.isEmpty(payeeName)) {
              item.payee = payeeName
            }
          })
        }
      },
      // 合同发生变化时带出合同下的主体
      getInvestorByContract(id) {
        console.log('合同ID:' + id)
        this.form.investorList = []
        // 获取当前合同的签约主体
        findMainBodyByContractId(id).then(response => {
          console.log(response)
          if (response.data !== undefined && response.data !== null && response.data.length > 0) {
            response.data.forEach(item => {
              const row = {
                id: undefined,
                type: item.investType,
                investorId: item.investMain,
                spvId: item.spvId,
                currency: item.currency,
                rateAmount: undefined,
                rate: undefined,
                exchangeRate: undefined,
                amount: 0,
                ratio: '',
                remark: ''
              }
              if (!(this.form.investorList instanceof Array)) {
                this.$set(this.form, 'investorList', [])
              }
              this.form.investorList.push(row)
            })
            // 加载万主体. 带出主体的汇率
            this.$nextTick(() => {
              this.form.investorList.forEach((item, index) => {
                if (item) {
                  // 获取该合同的币种
                  this.getContractCurrency(id, () => {
                    this.loadRate(index)
                  })
                }
              })
            })
          }
          this.changeInvestLength()
        })
      },
      async loadRate(index) {
        // 刷新是否展示多币种
        this.refreshDisplayExchangeRate()
        const sourceCurrency = this.form.investorList[index].currency
        await getWebRate(this.contractCurrency, sourceCurrency).then(response => {
          this.$set(this.form.investorList[index], 'placeholder', this.$t('汇率参考') + ': ' + response.data)
          this.$forceUpdate()
        })
      },
      // 加载合同下的收划款计划
      getContractChange(id) {
        if (id !== null && id !== undefined && id !== '') {
          this.dealContractPaymentLoading = true
          this.dealContractPlanList = []
          // 区分股权债权和参股基金
          console.log('当前会议划款类型: ', this.$route.query.dealType)
          if (this.$route.query.dealType === 'bf') {
            getDealContractPlanByMainIdBf(id).then(response => {
              this.loadContractPlanData(response.data)
            })
          } else if (this.$route.query.dealType === 'debt') {
            getDealContractDebt(id).then(response => {
              this.dealContractPlanList = []
              var data = response.data.dealContractPlanDebts
              if (data !== null && data.length > 0) {
                var temp = data[0].collectionTime
                if (temp === '' || temp === null || temp === undefined) {
                  this.dealContractPayColName = '划款'
                  data.forEach(item => {
                    var row = {
                      investId: item.investId,
                      investName: item.investName,
                      paymentTime: item.paymentTime,
                      paymentMoney: item.paymentMoney,
                      currency: item.currency,
                      remark: item.remark,
                      balance: 0
                    }
                    this.dealContractPlanList.push(row)
                  })
                } else {
                  this.dealContractPayColName = '收款'
                  data.forEach(item => {
                    var row = {
                      investId: item.investId,
                      investName: item.investName,
                      collectionTime: item.collectionTime,
                      collectionMoney: item.collectionMoney,
                      currency: item.currency,
                      remark: item.remark,
                      balance: 0
                    }
                    this.dealContractPlanList.push(row)
                  })
                }
              }
              this.getTheRemainingAmount(this.dealContractPlanList)
              this.dealContractPaymentLoading = false
            })
          } else {
            getDealContractPlanByMainId(id).then(response => {
              this.loadContractPlanData(response.data)
            })
          }
          this.loadForm()
        } else {
          this.loading = false
        }
      },
      //
      getContractMoney() {
        this.loading = true
        // 获取该合同的金额 记录下来
        this.form.contractAmount = 0
        if (this.form.contractId !== undefined && this.form.contractId !== '' && this.form.contractId !== null) {
          queryOaAndDealContractById(this.form.contractId).then(response => {
            if (response.data !== null && response.data.length > 0) {
              this.form.contractAmount = response.data[0].money
              if (this.form.contractPayables === null || this.form.contractPayables === undefined || this.form.contractPayables === '') {
                this.form.contractPayables = response.data[0].contractPayables
              }
              // 先决条件文本框
              this.paymentPrerequisites = response.data[0].paymentPrerequisites
              this.form.paymentPrerequisites = this.paymentPrerequisites
              if (response.data[0].isPayment === 'payment') {
                this.paymentPrerequisitesShow = true
              }
            }
            this.loading = false
            this.loadForm()
          })
        }
      },
      // 加载合同下的收划款计划
      loadContractPlanData(data) {
        if (data !== null && data.length > 0) {
          var temp = data[0].collectionTime
          if (temp === '' || temp === null || temp === undefined) {
            this.dealContractPayColName = '划款'
          } else {
            this.dealContractPayColName = '收款'
          }
        }
        this.getTheRemainingAmount(data)
        this.dealContractPaymentLoading = false
      },
      // 根据首划款计划的明细. 获取预划款还能录入多少金额
      getTheRemainingAmount(data) {
        // 将收划款计划合并成一条. 例如 主体名称 字节跳动有两条. 给他合并成一条. 预计划款金额也累计
        data = this.accumulatedEstimatedPaymentAmount(data)
        getTheRemainingAmount(this.thisDealId, this.form.contractId, this.form.id).then(response => {
          if (data !== undefined && data !== null && data.length > 0) {
            if (response.data === null || response.data.length <= 0) {
              // 如果还没参与过计算. 也就查不出来数据, 没有数据直接给最大值. 就是剩余金额
              data.forEach(item1 => {
                item1.balance = (item1.collectionMoney === null || item1.collectionMoney === undefined || item1.collectionMoney === '') ? item1.paymentMoney : item1.collectionMoney
              })
            } else {
              var listUp = {}
              var listDown = {}
              var upTable = response.data
              var downTable = data
              // 使用该合同的所有项目划款中的划款主图
              listUp.listId = []
              upTable.forEach(item => {
                if (listUp.listId.includes(item.investorId)) {
                  listUp[item.investorId] = this.checkFormatFloat(listUp[item.investorId]) + this.checkFormatFloat(item.amount)
                } else {
                  // 如果已存在实际划款金额. 就去实际划款金额参与计算  否则就去 投资主体中的划款金额参与计算
                  if (item.actualPaymentMoney !== undefined && item.actualPaymentMoney !== null && item.actualPaymentMoney !== '' && item.actualPaymentMoney !== 0) {
                    listUp[item.investorId] = this.checkFormatFloat(item.actualPaymentMoney)
                  } else {
                    listUp[item.investorId] = this.checkFormatFloat(item.amount)
                  }
                  listUp.listId.push(item.investorId)
                }
              })
              // 算出未划款金额剩余金额,  lisUp中存放的就是 其他划款中已经划款了的金额. 现在需要做的就是. 再划款计划里. 减掉这些值.
              downTable.forEach(item => {
                var moneyTemp = item.paymentMoney === null ? item.collectionMoney : item.paymentMoney
                if (listUp.listId.includes(item.investId)) {
                  item.balance = moneyTemp - listUp[item.investId]
                } else {
                  item.balance = 0
                }
              })
              console.log(listUp, listDown)
            }
          }
          this.dealContractPlanList = data
          this.form.dealContractPlanList = this.dealContractPlanList
          this.loadForm()
          // 刷新是否展示多币种
          this.refreshDisplayExchangeRate()
        })
      },
      /**
       * 将收划款计划合并成一条. 例如 主体名称 字节跳动有两条. 给他合并成一条. 预计划款金额也累计
       * @param data
       */
      accumulatedEstimatedPaymentAmount(data) {
        if (data !== undefined && data !== null) {
          var result = []
          var tempId = []
          data.forEach(item => {
            if (tempId.includes(item.investId)) {
              // 合并金额
              const object = result.find(obj => obj.investId === item.investId)
              var money = 0

              if (item.paymentMoney !== null) {
                money = item.paymentMoney
                object.paymentMoney = this.checkFormatFloat(object.paymentMoney) + this.checkFormatFloat(money)
              } else {
                money = item.collectionMoney
                object.collectionMoney = this.checkFormatFloat(object.collectionMoney) + this.checkFormatFloat(money)
              }
              // 合并时间
              var tempArr = []
              if (item.paymentTime !== undefined && item.paymentTime !== null) {
                tempArr.push(item.paymentTime)
                object.paymentTimeArr = tempArr
              }
              if (item.collectionTime !== undefined && item.collectionTime !== null) {
                tempArr.push(item.collectionTime)
                object.collectionTimeArr = tempArr
              }
            } else {
              result.push(item)
              tempId.push(item.investId)
            }
          })
          return result
        }
        return data
      },
      viewContractPage(id) {
        if (id !== null && id !== '' && id !== undefined) {
          if (this.$route.query.dealType === 'bf') {
            // 根据合同ID 查出对应的合同
            findActIdByContractIdBf(id).then(response => {
              this.contractPageLoading = true
              this.$nextTick(() => {
                var proData = {}
                proData.actId = response.data
                this.$refs.processInfoForm.init(proData)
              })
            })
          } else {
            // 根据合同ID 查出对应的合同
            findActIdByContractId(id).then(response => {
              if (response.data === null || response.data === undefined || response.data === '') {
                this.contractView = true
              } else {
                this.contractPageLoading = true
              }
              this.$nextTick(() => {
                var proData = {}
                proData.actId = response.data
                if (this.isEmpty(proData.actId)) {
                  // 查看表单页面
                  getDealContract(id).then(res => {
                    this.$refs.dealContractForm.init({ id: res.data.id })
                  })
                } else {
                  // 查看审批页面
                  this.$refs.processInfoForm.init(proData)
                }
              })
            })
          }
        } else {
          this.msgError(this.$t('请先选择一个合同!'))
        }
      },
      // 划款时间维护 : 按钮获取数据
      updatePayTimeBtn(data) {
        this.MaintainPaymentInforLoading = true
        this.MaintainPaymentInforTitle = data.actTitle + ' - ' + data.userName + ' (' + this.formatCurrency(data.currency) + ')'
        this.$nextTick(() => {
          this.$refs.MaintainPaymentInfor.parentCurrency = data.currency
          this.$refs.MaintainPaymentInfor.init(data, 'deal_payment')
          this.$refs.MaintainPaymentInfor.actTaskShowTimeBtn = true
        })
      },
      // 划款时间维护 : 保存到后台
      updatePayTimeSuccess(data) {
        updatePayTime(data).then(respones => {
          if (respones.code === 200) {
            this.MaintainPaymentInforLoading = false
            try {
              this.closeForm()
            } catch (e) {
              this.init(this.form)
            }
          } else {
            this.msgSuccess(this.$t('维护失败'))
          }
        })
      },
      checkFormatFloat(val) {
        if (val !== undefined && val !== null && val !== '' && !isNaN(parseFloat(val))) {
          return parseFloat(val)
        }
        return 0
      },
      formatCurrency(val) {
        const currency = this.currencyOptions.find(obj => obj.dictValue === val)
        if (currency) {
          return currency.dictLabel
        }
        return val
      },
      // 根据划款金额和汇率计算划款金额
      rateAmountCalculate(rateAmount, rate, index, flag) {
        if (rateAmount !== undefined && rateAmount !== null && rateAmount !== '' && !isNaN(parseFloat(rateAmount)) && rate !== undefined && rate !== null && rate !== '' && !isNaN(parseFloat(rate))) {
          if (this.form.investorList[index].rateAmount === undefined || this.form.investorList[index].rateAmount === null || this.form.investorList[index].rateAmount === '' || flag) {
            this.form.investorList[index].rateAmount = (parseFloat(rateAmount) * parseFloat(rate)).toFixed(6)
            this.$forceUpdate()
          }
        }
      },
      // 根据划款金额和划款金额计算汇率
      getExchangeRate(money, rateAmount, rate, index) {
        if (rateAmount !== undefined && rateAmount !== null && rateAmount !== '' && !isNaN(parseFloat(rateAmount)) && money !== undefined && money !== null && money !== '' && !isNaN(parseFloat(money))) {
          if (parseFloat(money) !== 0 && parseFloat(rateAmount) !== 0 && (rate === undefined || rate === null || rate === '' || rate === 0)) {
            console.log('-------', rateAmount, money)
            this.form.investorList[index].exchangeRate = (parseFloat(rateAmount) / parseFloat(money)).toFixed(6)
            this.$forceUpdate()
          }
        }
      }

    }
  }
</script>
<style lang="scss" scoped>
.el-autocomplete .el-input__icon{
  display: none;
}
/deep/ .el-form-item__content{
  margin-left: 0 !important;
}
</style>
